#!/usr/bin/env bash

set -e

# White
msg() {
    echo -e "$@"
}

# Yellow
info() {
    printf "\033[1;33m$@\033[0m\n"
}

# Green
success() {
    printf "\033[0;32m$@\033[0m\n"
}

# Red
fail() {
    printf "\033[0;31m$@\033[0m\n"
    exit 1
}

add_to_file() {
    grep -qF -- "$1" "$2" || echo "$1" >> "$2"
}

info "Preparing to install flowpilot..."

# fix apt
add_to_file "nameserver 8.8.8.8" /etc/resolv.conf

groupadd -g 3001 aid_bt || true
groupadd -g 3002 aid_bt_net || true
groupadd -g 3003 aid_inet || true
groupadd -g 3004 aid_net_raw || true
groupadd -g 3005 aid_admin || true

usermod -a -G aid_bt,aid_bt_net,aid_inet,aid_net_raw,aid_admin root || true
usermod -g 3003 _apt || true

add_to_file "export ANDROID_DATA=''" ~/.bashrc
add_to_file "export PIP_ROOT_USER_ACTION=ignore" ~/.bashrc
export ANDROID_DATA=''
export PIP_ROOT_USER_ACTION=ignore

apt update && apt install -y sudo git
DEBIAN_FRONTEND=noninteractive apt-get install -y tzdata
sudo apt install -y software-properties-common
yes | sudo add-apt-repository ppa:deadsnakes/ppa || true
sudo apt install -y python3.9 python3.9-dev python3.9-distutils python-is-python3 python3-pip
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.9 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 1

cd ~/ && [ ! -d 'flowpilot' ] && git clone https://github.com/flowdriveai/flowpilot.git || true
cd ~/flowpilot && git submodule update --init

echo "set -g mouse on" >> .tmux.conf # enable mouse scrolling in tmux

./get_dependencies.sh
scons

success "Flowpilot successfully installed. launch using cd flowpilot && ./launch_flowpilot.sh"
